
#include <QCoreApplication>
#include <QLibraryInfo>
#include <QTranslator>
#include <QPointer>
#include <QStringList>
#include <QDebug>

#include "translator.h"

QList<QPointer<QTranslator>> g_translators;

static void CleanupTranslator()
{
    while (!g_translators.isEmpty()) {
        QPointer<QTranslator> translator = g_translators.takeFirst();
        if (!translator.isNull()) {
            translator->deleteLater();
        }
    }
}

Translator::Translator(QObject *parent) : QObject{parent}
{
}

void Translator::LoadLanguage(const QString &filename, const QString &language)
{
    qAddPostRoutine(CleanupTranslator);

    QLocale locale(language);
    QStringList translate_files;
    QStringList translation_pathes;

    translate_files << "qt";
    if (language == "zh_TW") {
        translate_files << "qtbase";
    }
    if (!filename.isEmpty()) {
        translate_files << filename;
    }

    translation_pathes << ":/i18n";
    translation_pathes << QString("%1/translations").arg(QCoreApplication::applicationDirPath());
    translation_pathes << QLibraryInfo::location(QLibraryInfo::TranslationsPath);

    // qDebug().noquote() << "TranslateFile:" << translate_files.join(", ");
    // qDebug().noquote() << "TranslateFile Search Path:" << translation_pathes.join(", ");

    bool loaded = false;
    for (const QString &translate_file : qAsConst(translate_files)) {
        for (const QString &translations_path : qAsConst(translation_pathes)) {
            loaded = false;
            QPointer<QTranslator> translator = new QTranslator();
            if (!loaded) {
                loaded = translator->load(locale, translate_file, "_", translations_path, ".qm");
            }
            if (!loaded) {
                loaded = translator->load(locale, translate_file, ".", translations_path, ".qm");
            }
            if (loaded) {
                if (qApp->installTranslator(translator)) {
                    qDebug().noquote() << "Translator:" << QString("Load language %1 from %2").arg(language, translate_file);
                    g_translators.append(translator);
                } else {
                    qWarning().noquote() << QString("Load language %1 from %2 failed!").arg(language, translate_file);
                }
                break;
            }
        }
        if (!loaded) {
            qWarning().noquote() << QString("Cannot find translation file %1 for language %2, skip!").arg(translate_file, language);
        }
    }
}
